#include <stdlib.h>
#include <stdio.h>

#include "fnct.h"

#define M 4
#define N 4
#define MAX 65536

void young_matrixify(TYPE **A, int i, int j, int m, int n){
	if(i < 0 || j < 0 || i > m || j > n)
		return;
	TYPE max = A[i][j];
	if(i == m && j == n){
		return;
	}else if(i == m && j < n){
		if(A[i][j] > A[i][j+1]){
			swap(&A[i][j], &A[i][j+1]);
			young_matrixify(A, i, j+1, m, n);	
		}
	} else if(i < m && j == n){
		if(A[i][j] > A[i+1][j]){
			swap(&A[i][j], &A[i+1][j]);
			young_matrixify(A, i+1, j, m, n);	
		}
	} else if(i < m && j < n){
		if(A[i][j+1] > max) max = A[i][j+1];
		if(A[i+1][j] > max) max = A[i+1][j];
		if(max == A[i][j+1]){
			swap(&A[i][j], &A[i][j+1]);
			young_matrixify(A, i, j+1, m, n);	
		}
		if(max == A[i+1][j]){
			swap(&A[i][j], &A[i+1][j]);
			young_matrixify(A, i+1, j, m, n);	
		}
	}
}

TYPE extract_min(TYPE **A, int row, int col){
	int m = row - 1;
	int n = col - 1;
	if(m < 0 || n < 0 || row > M || col > N)
		return MAX;
	TYPE ret = A[0][0];
	A[0][0] = A[m][n];
	A[m][n] = MAX;
	young_matrixify(A, 0, 0, m, n);
	return ret;
}

int main(void){
	TYPE a[M][N] = {2, 4, 9, 12, 3, 5, 14, MAX, 8, 16, MAX, MAX, MAX, MAX, MAX, MAX};
	//打印数组a,可以看出它符合young氏矩阵的定义
	print_two_array((TYPE **)a, M, N); 
    	//第一次取出最小值
    	extract_min((TYPE **)a, M, N);
    	//打印取出最小值之后的young氏矩阵
	print_two_array((TYPE **)a, M, N); 
    	//再次取出最小值
    	extract_min((TYPE **)a, M, N);
    	//打印取出最小值之后的young氏矩阵
    	print_two_array((TYPE **)a, M, N); 
	exit(0);
}
